$(function () {
  var id = sessionStorage.getItem("id");
  var token = sessionStorage.getItem("token");

  axios
    .get(`http://localhost:9000/users/info?id=${id}`, {
      headers: {
        authorization: token,
      },
    })
    .then(res => {
      if (res.data.code === 1) {
        $(".username").val(res.data.user.username);
        $(".age").val(res.data.user.age);
        $(".gender").val(res.data.user.gender);
        $(".nickname").val(res.data.user.nickname);
      }
    });
  $("form").on("submit", function (event) {
    event.preventDefault();
    var username = $('input[name="username"]').val();
    var age = $('input[name="age"]').val();
    var gender = $('select[name="gender"]').val();
    var nickname = $('input[name="nickname"]').val();

    if (!username || !age || !gender || !nickname) {
      alert("请填写所有必填项");
      return;
    }

    axios
      .post(
        "http://localhost:9000/users/update",
        {
          id: id,
          age: age,
          gender: gender,
          nickname: nickname,
        },
        {
          headers: {
            authorization: token,
          },
        }
      )
      .then(function (response) {
        if (response.data.code === 1) {
          alert(response.data.message);
          sessionStorage.setItem("nickname", nickname);
        } else {
          alert(response.data.message);
        }
      });
  });
});
